﻿using Nancy;
using Nancy.Bootstrapper;
using Nancy.Session;
using Nancy.TinyIoc;
using System;
using System.Linq;
using System.Reflection;

namespace TaskManagementSystem
{
    public class Bootstrap : DefaultNancyBootstrapper
    {
        /// <summary>
        /// Adding a custom favicon
        /// </summary>
        protected override byte[] FavIcon
        {
            get { return null; }
        }


        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
        }

        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            StaticConfiguration.DisableErrorTraces = false;
            pipelines.OnError.AddItemToStartOfPipeline(CatchUnhandleException());
            ModuleSecurity.Enable(pipelines);
            CookieBasedSessions.Enable(pipelines);

            ScheduledTask.ScheduledTaskManager.LoadData();
            ScheduledTask.ScheduledTaskManager.Start();
        }

        protected override void ConfigureConventions(Nancy.Conventions.NancyConventions nancyConventions)
        {
        }

        protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {

        }
        
        public static Func<NancyContext, System.Exception, Response> CatchUnhandleException()
        {
            return (ctx, ex) =>
            {
                Logs.Loggers.Weblogger.Fatal(ex);
                return new Response
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    ContentType = "text/html",
                    Contents = stream => ErrorResponse.FromMessagePath(stream, "Content/500.html")
                };
            };
        }
    }
}